package ren.yugong.fileutil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class TxtTemplateWriteStream<T> {

    private Class<T> txtTemplateCls;
    private File file;
    private TxtTemplateModel template;
    private BufferedWriter writer;

    public TxtTemplateWriteStream(Class<T> txtTemplateCls, File file) {
        this.txtTemplateCls = txtTemplateCls;
        this.file = file;
    }

    public void open() throws IOException {
        this.template = TxtTemplateFactory.getTemplate(this.txtTemplateCls);
        Charset charset = Charset.forName(template.getCharset());
        Path path = Paths.get(file.getPath());
        writer = Files.newBufferedWriter(path, charset);
    }

    public void write(List<T> list) {
        list.forEach(l -> write(l));
    }

    public void write(T t) {
        String line = TxtLineObject.line(t);
        try {
            writer.write(line + template.getLineSeparator());
        } catch (IOException e) {
            throw new TemplateCommonException(e);
        }
    }

    public void close() {
        if (null != writer) {
            try {
                writer.close();
            } catch (IOException e) {
                throw new TemplateCommonException(e);
            }
        }
    }


}
